<template>
  <div class="page-box">
    <el-card class="page-box-card">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        label-width="88px"
        inline
        @submit.native.prevent
      >
        <el-form-item label="分类名称" prop="param.name">
          <el-input
            v-model="queryParams.param.name"
            placeholder="请输入分类名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="small"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['definition:class:add']"
            >新增</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleEdit"
            v-hasPermi="['definition:class:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['definition:class:delete']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload2"
            size="mini"
            v-hasPermi="['definition:class:upload']"
            @click="handleImport"
            >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            v-hasPermi="['definition:class:download']"
            @click="downloadData"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="dataList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />
        <el-table-column prop="orderNum" label="排序" width="60" fixed="left">
        </el-table-column>
        <el-table-column prop="name" label="分类名称" width="180" fixed="left">
        </el-table-column>
        <el-table-column prop="parentId" label="父级ID" width="180">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ $moment(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人"> </el-table-column>
        <el-table-column prop="updateTime" label="最后修改" width="180">
          <template slot-scope="scope">
            {{ $moment(scope.row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column prop="updateBy" label="修改人"> </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="140">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.row)"
              v-hasPermi="['system:dept:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              style="color: red"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:dept:edit']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改部门对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="addDialog"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="addForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="分类名称" prop="name">
              <el-input
                v-model="addForm.name"
                placeholder="请输入分类名称"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="排序" prop="orderNum">
              <el-input-number
                style="width: 100%"
                v-model="addForm.orderNum"
                :min="1"
                label="请输入分类排序"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="父级分类" prop="tag">
              <el-cascader
                style="width: 100%"
                v-model="addForm.parentIds"
                :props="props"
                :options="treeData"
                :show-all-levels="false"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 接口分类导入 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  insertCategory,
  updateCategory,
  deleteCategory,
  listCategory,
  treeCategory,
  importData,
  exportData,
} from "@/api/collect/classification";
import { getToken } from "@/utils/auth";
export default {
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      selectionData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        param: {
          name: "",
        },
      },
      props: {
        checkStrictly: true,
        label: "name",
        value: "id",
      },
      dataList: [],
      total: 0,
      treeData: [],
      title: "",
      addDialog: false,
      addForm: {
        name: "",
      },
      rules: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
      },
      // 变量导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（变量导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的变量数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + importData,
      },
    };
  },
  created() {
    this.getList();
    this.getTreeData();
  },
  methods: {
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 导入数据
    handleImport() {
      this.upload.title = "接口分类导入";
      this.upload.open = true;
    },
    // 导出数据
    downloadData() {
      const that = this;
      this.$modal.confirm("是否确认导出当前查询条件下的数据？").then(() => {
        // 导出
        const params = that.queryParams;
        // return that.download(exportData, { ...params }, `接口分类.xlsx`);
        exportData({ ...params })
          .then((res) => {
            // const url = window.URL.createObjectURL(new Blob([res]));
            const blob = new Blob([res]);
            this.$download.saveAs(blob, "接口分类数据.xlsx");
            this.$message.success("导出成功");
          })
          .catch((error) => {
            this.$message.success("下载Excel失败:", error);
            console.error("下载Excel失败:", error);
          });
      });
    },
    getTreeData() {
      treeCategory({}).then((res) => {
        this.treeData = [...res.data];
        // console.log("树状数据: ");
      });
    },
    // 搜索事件
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置事件
    resetQuery() {
      this.dataList = [];
      this.total = 0;
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 获取数据列表
    getList() {
      this.loading = true;
      const param = { ...this.queryParams };
      console.log("param: ", param);
      listCategory(param).then((response) => {
        console.log("response: ", response);
        this.dataList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 列表选中事件
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.selectionData = [...selection];
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 新增分类
    handleAdd() {
      this.title = "新增分类";
      this.addDialog = true;
    },
    // 新增/修改弹框提交事件
    submitForm() {
      const param = { ...this.addForm };
      param.parentId =
        param.parentIds && param.parentIds.length
          ? param.parentIds[param.parentIds.length - 1]
          : null;
      if (param.id) {
        // 修改
        updateCategory(param).then((res) => {
          this.$message.success("修改成功");
          this.cancel();
          this.handleQuery();
          this.getTreeData();
        });
      } else {
        // 新增
        insertCategory(param).then((res) => {
          this.$message.success("新增成功");
          this.cancel();
          this.handleQuery();
          this.getTreeData();
        });
      }
    },
    // 新增/修改弹框取消事件
    cancel() {
      this.addForm = {
        name: "",
      };
      this.addDialog = false;
    },
    // 修改分类
    handleEdit(row) {
      this.title = "修改分类";
      const data = row.id ? row : this.selectionData[0];
      const ancestors = data.ancestors.split(",");
      ancestors.shift();
      this.addForm = {
        name: data.name,
        id: data.id,
        parentId: [data.parentId],
        orderNum: data.orderNum,
        parentIds: ancestors,
      };
      this.addDialog = true;
    },
    // 删除分类
    handleDelete(row) {
      const idList = row.id ? [row.id] : [...this.ids];
      this.$modal
        .confirm("是否确认删除当前选择的分类？")
        .then(function () {
          // 删除
          return deleteCategory({ idList });
        })
        .then(() => {
          this.$message.success("删除成功");
          this.getTreeData();
          this.handleQuery();
        })
        .catch(() => {});
    },
  },
};
</script>
